//
//  WCChooseTimeVC.m
//  WC
//
//  Created by wsj2015 on 15/9/18.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCChooseTimeVC.h"

#import "Macros.h"
#import "WCDateMdoel.h"
#import "WCDayModel.h"
#import "WCServiceTimeHeaderView.h"
#import "WCServiceTimeCell.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
#import "WCPopupLayerManager.h"
#import "WCNMeSetTimes(replace)VC.h"


static NSString *cellId = @"ServiceTimeCellId";
static NSString *headerId = @"WCServiceTimeHeaderView";
static NSString *footerId = @"UICollectionReusableView";


@interface WCChooseTimeVC ()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    UICollectionView *_collectionView;
    
    NSMutableArray *_dayArray;
    
    NSString *_timePeriod;
    
    
}

@end

@implementation WCChooseTimeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor =kAppBg;
    
    [self configNav];
    [self createCollectionView];
    [self prePareDataWith:self.dataArray];
    
    
    
}
- (void)configNav
{
//    [self  isShowPageBack:YES];
//    [self setTitleLabel:@"服务时间选择" width:180];
//    [self addNavBtn:CGRectMake((kScreenWidth) -50, 30,45, 30) title:@"确认" target:self action:@selector(confirmAction)];
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    self.title = @"服务时间选择";
    _dayArray =[NSMutableArray array];
    

}

- (void)prePareDataWith:(NSArray *)dataArray
{
  
    for (int i = 0; i <7 ; i++) {
        WCDayModel *model =[[WCDayModel alloc]init];
        model.weekDayId =[NSString stringWithFormat:@"%d",i + 1];
        
        NSMutableArray *array =[NSMutableArray array];
        for (WCDateMdoel *dateModel in dataArray) {
            if ([dateModel.weekDayId intValue] == i+1) {
                //给 天模型 日期设值 只需要设置一次
                if (!model.date) {
                    model.date =dateModel.date;
                }
                
                [array addObject:dateModel];
            }
        }
        model.dateArray =array;
        [_dayArray addObject:model];
       
    }
     [self sortedDate:_dayArray ];
//     [self delectVaildDayFromDayArray:_dayArray];
     [_collectionView reloadData];
   
   

}
//排序
- (void)sortedDate:(NSMutableArray *)array
{
    
    for (int i =0 ; i<array.count; i++) {
        for (int j =  i+1; j<array.count; j ++) {
            WCDayModel *model1 =array[i];
            WCDateMdoel *model2 =array[j];
          
            if ([model1.weekDayId integerValue] > [model2.weekDayId integerValue]) {
                [array exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
            
        }
//        如果星期六和星期 天 放前面
        WCDayModel *model =array[i];
        if ([model.weekDayId integerValue] ==6) {
            [array removeObject:model];
            [array insertObject:model atIndex:0];
        }if ([model.weekDayId integerValue] ==7) {
            [array removeObject:model];
            [array insertObject:model atIndex:1];

        }
        
    }
   
   
    
}
//删除 空的天
//- (void)delectVaildDayFromDayArray:(NSMutableArray *)dataArray
//{
//    if (dataArray.count==0) {
//        return;
//    }
//    for (WCDayModel *day in dataArray) {
//        if (day.dateArray.count == 0) {
//            [dataArray removeObject:day];
//        }
//    }
//    
//    [_collectionView reloadData];
//}
- (void)createCollectionView
{
    CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight -64);
    
    //init UICollectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.itemSize = CGSizeMake((frame.size.width-2.0f)/3.0f, 50);
    flowLayout.headerReferenceSize = CGSizeMake(frame.size.width, 33);
    flowLayout.footerReferenceSize = CGSizeMake(frame.size.width, 20);
    
    //init UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor whiteColor];
    
    UINib *nib = [UINib nibWithNibName:@"WCServiceTimeCell" bundle:nil];
    [collectionView registerNib:nib forCellWithReuseIdentifier:cellId];
    
    UINib *header = [UINib nibWithNibName:@"WCServiceTimeHeaderView" bundle:nil];
    [collectionView registerNib:header forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    
    
    
    
    _collectionView = collectionView;
    [self.view addSubview:collectionView];
    
    
}
- (void)confirmAction
{
    if (_collectionView.indexPathsForSelectedItems.count == 0) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"您还没选定一个时间段~" withView:self.view];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
    if (self.callBack) {
        NSString *timePeriod_tem =@"";
        if (_timePeriod) {
            timePeriod_tem =_timePeriod;
        }
        NSLog(@"%@###%@",_timePeriodId,_apptDate);
        self.callBack(_timePeriodId,_apptDate,timePeriod_tem);
    }
    

}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
//    int i = 0;
//    if (_dayArray) {
//     
//        for (WCDayModel *day in _dayArray) {
//            if( day.dateArray.count){
//                i ++;
//            }
//        }
//    }
//   
    
    return _dayArray.count;;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    WCDayModel *day =_dayArray[section];
    return day.dateArray.count;


}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WCServiceTimeCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    
    WCDayModel *dayModel =_dayArray[indexPath.section];
    WCDateMdoel *model =dayModel.dateArray[indexPath.row];
    //如果是传进来的时间段 该cell 为选定状态
   
    if ([self isSelectdItem:model]) {
        NSLog(@"第%li,%li",indexPath.section,indexPath.row);
        [cell setSelected:YES];
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }
    
    
    [cell configWithMode:model];
    
    return cell;
    
}

- (BOOL)isSelectdItem:(WCDateMdoel *)model
{
      if ([[NSString stringWithFormat:@"%@",model.timePeriodId] isEqualToString:[NSString stringWithFormat:@"%@",self.timePeriodId]] && [model.date isEqualToString:_apptDate]) {
          return YES;
      }
    return NO;
}
   
   
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        
        WCServiceTimeHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        WCDayModel *day =_dayArray [indexPath.section];
        header.timeLabel.text = day.date;
        
        return header;
    } else if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        footer.backgroundColor = kBorderColor;
        return footer;
    }
    
    return nil;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WCDayModel *day =_dayArray[indexPath.section];
    WCDateMdoel *model =day.dateArray[indexPath.row];
    _timePeriodId =model.timePeriodId;
    _apptDate =model.date;
    _timePeriod =model.timePeriod;


}

@end
